<template>
  <div class="page-score-prod-info">
    <!-- 步骤 -->
    <div class="post-step">
      <div
        class="step-item"
        :class="{'active': postingSteps === 1 || postingSteps === 2}"
      >
        <!-- 01、选择商品类目 -->
        <div class="step-txt">
          01、{{ $t("product.selectProductCategory") }}
        </div>
      </div>
      <div
        class="step-item"
        :class="{'active': postingSteps === 2}"
      >
        <!-- 02、编辑商品信息 -->
        <div class="step-txt">
          02、{{ $t("product.editProductInfo") }}
        </div>
      </div>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      @submit.prevent
    >
      <!-- 基本信息  -->
      <div
        v-show="postingSteps === 1"
        class="tittle"
      >
        {{ $t("product.basicInformation") }}
      </div>

      <div
        v-show="postingSteps === 1"
        class="basic-info"
      >
        <!-- 选择语言 -->
        <el-form-item
          v-show="postingSteps === 1"
          :label="$t('product.selectLanguage')"
        >
          <el-select
            v-model="curLang"
            multiple
            :placeholder="$t('product.tip1')"
            class="select-lang"
            @change="onSelectLang"
          >
            <el-option
              v-for="item in langOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <div class="el-form-item-tips">
            {{ $t("product.postProductTips2") }}
          </div>
        </el-form-item>

        <div
          v-show="postingSteps === 1"
          class="prod-name-box"
        >
          <el-form-item
            :label="$t('product.prodName')"
            prop="prodNameCn"
            class="prod-name-con is-required"
          >
            <el-input
              v-model="prodNameCn"
              class="prod-name-input"
              maxlength="60"
            />
            <!-- <div class="el-form-item-tips">{{ $t("product.postProductTips3") }}</div> -->
            <div class="el-form-item-tips">
              商品名称建议：商品描述+属性，长度不超过60个字符
            </div>
          </el-form-item>
          <el-form-item
            v-if="curLang.includes(2)"
            label-width="0"
            prop="prodNameEn"
            class="prod-name-con"
          >
            <el-input
              v-model="prodNameEn"
              class="prod-name-input"
              maxlength="60"
            />
            <div class="el-form-item-tips">
              The suggestion: description + attribute, length cannot exceed 60
            </div>
          </el-form-item>
        </div>
        <!-- 商品卖点 -->
        <div
          v-show="postingSteps === 1"
          class="prod-name-box"
        >
          <el-form-item
            :label="$t('product.productSellingPoints')"
            prop="briefCn"
            class="prod-name-con"
          >
            <el-input
              v-model="briefCn"
              class="prod-name-input"
              maxlength="100"
            />
            <!-- <div class="el-form-item-tips">{{ $t("product.postProductTips4") }}</div> -->
            <div class="el-form-item-tips">
              商品卖点展示在商品名称下面，长度不超过100个字符
            </div>
          </el-form-item>
          <el-form-item
            v-if="curLang.includes(2)"
            label-width="0"
            prop="briefEn"
            class="prod-name-con"
          >
            <el-input
              v-model="briefEn"
              class="prod-name-input"
              maxlength="100"
            />
            <div class="el-form-item-tips">
              Displayed under the title, the length cannot exceed 100
            </div>
          </el-form-item>
        </div>
        <el-form-item
          v-show="postingSteps === 1"
          :label="$t('product.pic')"
          prop="imgs"
        >
          <imgs-upload
            v-model="dataForm.imgs"
            :limit="9"
          />
          <span>{{ $t("category.recPicSize") }}800*800，{{ $t("product.picUploadTips") }}</span>
        </el-form-item>
        <el-form-item
          v-show="postingSteps === 1"
          :label="$t('product.productVideo')"
        >
          <!-- 视频组件 -->
          <video-upload v-model="dataForm.video" />
          <div
            v-if="dataForm.video"
            class="video-del-btn default-btn"
            @click="onDeleteVideo"
          >
            删除视频
          </div>
        </el-form-item>
      </div>

      <!-- 规格库存 -->
      <div
        v-show="postingSteps === 1"
        class="tittle"
      >
        {{ $t("product.specificationStock") }}
      </div>

      <div
        v-show="postingSteps === 1"
        class="basic-info"
      >
        <sku-tag
          v-show="postingSteps === 1"
          ref="skuTagRef"
          :sku-list="dataForm.skuList"
          @change="onChangeSkuTagSkuHandler"
        />
        <sku-table
          v-show="postingSteps === 1"
          ref="skuTableRef"
          v-model="dataForm.skuList"
          v-model:prodNameCn="prodNameCn"
          v-model:prodNameEn="prodNameEn"
        />
      </div>

      <!-- 物流信息  -->
      <div
        v-show="postingSteps === 1"
        class="tittle"
      >
        {{ $t("order.logisticsInformation") }}
      </div>

      <div
        v-show="postingSteps === 1"
        class="basic-info"
      >
        <prod-transport
          v-show="dataForm.deliveryMode.hasShopDelivery&&postingSteps === 1"
          :transport-data="dataForm"
          @change-info="onChangeInfo"
        />
      </div>

      <el-tabs
        v-show="postingSteps === 2"
        type="card"
      >
        <el-tab-pane :label="$t('product.chineseInf')">
          <el-form-item
            :label="$t('homes.productDetails')"
            prop="contentCn"
          >
            <div class="prod-det-box">
              <div class="prod-content">
                <tiny-mce
                  ref="contentCnRef"
                  v-model="contentCn"
                  :width="850"
                  :height="600"
                />
              </div>

              <!-- 详情预览 -->
              <div class="details-preview">
                <div class="preview-box-title">
                  {{ $t('sysManagement.DetailspagePreviewImage') }}
                </div>
                <div
                  v-rich="contentCn"
                  class="preview-con"
                />
              </div>
            </div>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane :label="$t('sysManagement.englishInformation')">
          <el-form-item
            label="Product details"
            prop="contentEn"
          >
            <div class="prod-det-box">
              <div class="prod-content">
                <tiny-mce
                  ref="contentEnRef"
                  v-model="contentEn"
                  :height="600"
                  :width="850"
                />
              </div>

              <!-- 详情预览 -->
              <div class="details-preview">
                <div class="preview-box-title">
                  {{ $t('sysManagement.DetailspagePreviewImage') }}
                </div>
                <div
                  v-rich="contentEn"
                  class="preview-con"
                />
              </div>
            </div>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <!-- 底部固定操作栏 -->
    <div class="prod-footer">
      <div class="foot">
        <div class="inner">
          <div v-if="postingSteps === 1">
            <div
              class="default-btn save-btn"
              @click="onSubmit"
            >
              {{ $t("product.saveBtn1") }}
            </div>
            <div
              class="default-btn primary-btn"
              @click="nextStep"
            >
              {{ $t("product.nextStep2") }}
            </div>
          </div>
          <div v-if="postingSteps === 2">
            <div
              class="default-btn save-btn"
              @click="prevStep"
            >
              {{ $t("product.prevStep") }}
            </div>
            <div
              class="default-btn primary-btn"
              @click="onSubmit"
            >
              {{ $t("product.saveBtn1") }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import ProdTransport from '../../../prod/prod/components/prod-transport.vue'
import { useCommonStore } from '@/stores/common.js'
import { validHtmlLength } from '@/utils/index.js'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const emit = defineEmits(['refreshDataList'])
// 规格列表
// 语言选项
const langOptions = [{
  value: 1,
  label: '简体中文'
}, {
  value: 2,
  label: 'English'
}]

const dataRule = {
  imgs: [
    { required: true, message: $t('product.plePictureToUpload'), trigger: 'blur' }
  ]
}

const dataFormRef = ref(null)
let validPic = false
const dataForm = ref({
  deliveryAmount: 0.01,
  tableRate: -1,
  prodName: '',
  brief: '',
  video: '',
  pic: '',
  imgs: '',
  categoryId: route.query.categoryId ? parseInt(route.query.categoryId) : null,
  shopCategoryId: null, // 店铺分类id
  prodId: 0,
  prodScore: 0,
  scorePrice: 0,
  skuList: [],
  scoreProdType: 0,
  content: '',
  deliveryMode: {
    hasShopDelivery: true,
    hasUserPickUp: false,
    hasCityDelivery: false
  },
  prodNameEn: '',
  prodNameCn: '',
  contentEn: '',
  contentCn: '',
  briefEn: '',
  briefCn: '',
  isCheck: false,
  value: false,
  isSubmit: false,
  skuPartyCodes: true,
  deliveryTemplateId: -1
})
watch(() => dataForm.value.imgs, () => {
  if (validPic) {
    dataFormRef.value.validateField('imgs')
  }
})
let isSubmit = false
onMounted(() => {
  validPic = false // 初始化不验证是否选择图片
  dataForm.value.prodId = route.query.prodId
  isSubmit = false
  onGetDataList()
})

// 上一步
const postingSteps = ref(1)

const prevStep = () => {
  postingSteps.value = 1
}
// 下一步
const prodNameCn = ref('')
const contentEn = ref('')
const contentCn = ref('')
const value = ref('')
let isValue = ''

const nextStep = () => {
  validPic = true // 用于解决选择图片提示不隐藏问题
  dataFormRef.value.validate(() => {
    if (!prodNameCn.value) {
      onErrorMsg($t('product.pleEnterProdName'))
      return
    }
    if (!dataForm.value.imgs) {
      onErrorMsg($t('product.plePictureToUpload'))
      return
    }
    // 校验sku列表
    onCheckSkuList()
    if (isCheck) {
      onErrorMsg(isValue)
      return
    }
    if ((dataForm.value.deliveryAmount === 0 || dataForm.value.deliveryAmount === '' || dataForm.value.deliveryAmount === null) && dataForm.value.tableRate === -1) {
      // 请选择运费模板
      onErrorMsg($t('menuList.pleaseEnterTheAmount'))
      return
    }
    if (dataForm.value.deliveryMode.hasShopDelivery && dataForm.value.tableRate > 0 && !dataForm.value.deliveryTemplateId) {
      onErrorMsg($t('product.pleShgTlate'))
      return
    }

    dataForm.value.contentCn = contentCn.value
    dataForm.value.contentEn = contentEn.value
    if (validHtmlLength(dataForm.value.contentCn) || validHtmlLength(dataForm.value.contentEn)) {
      return
    }
    postingSteps.value = 2
  })
}
/**
 * 选择语言(中文信息必填)
 */
const curLang = ref([1])
const onSelectLang = (value) => {
  if (!value.length) {
    curLang.value = [1]
    return
  }
  curLang.value = JSON.parse(JSON.stringify(value))
  if (!curLang.value.find(el => el === 2)) {
    dataForm.value?.prodLangList?.forEach((el) => {
      if (el.lang === 1) {
        el.prodNameEn = ''
        el.briefEn = ''
        dataForm.value.briefEn = ''
        dataForm.value.prodNameEn = ''
      }
    })
  }
  if (!curLang.value.find(el => el === 1)) {
    curLang.value.unshift(1)
  }
}
// 获取分类数据
const prodNameEn = ref('')
const briefEn = ref('')
const briefCn = ref('')
const skuTagRef = ref(null)
const skuTableRef = ref(null)
const contentCnRef = ref(null)
const contentEnRef = ref(null)
const onGetDataList = () => {
  if (dataForm.value.prodId) {
    // 获取产品数据
    http({
      url: http.adornUrl(`/prod/prod/info/${dataForm.value.prodId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      dataForm.value.prodLangList.forEach(prodLang => {
        if (prodLang.lang === 0) {
          prodNameCn.value = prodLang.prodName
          briefCn.value = prodLang.brief
          contentCn.value = prodLang.content
        }
        if (prodLang.lang === 1) {
          prodNameEn.value = prodLang.prodName
          briefEn.value = prodLang.brief
          contentEn.value = prodLang.content
        }
      })
      dataForm.value.deliveryMode = JSON.parse(data.deliveryMode)
      dataForm.value.deliveryMode.hasShopDelivery = true
      skuTagRef.value.init(data.skuList)
      dataForm.value.skuList.forEach(sku => {
        sku.oriStock = sku.stocks
        sku.skuLangList.forEach(skulang => {
          if (skulang.lang === 0) {
            sku.prodNameCn = skulang.prodName
          } else {
            sku.prodNameEn = skulang.prodName
          }
        })
      })
      skuTableRef.value.init(dataForm.value?.skuList)
    })
  } else {
    nextTick(() => {
      dataFormRef.value.resetFields()
      skuTagRef.value?.init()
      dataForm.value.pic = ''
      dataForm.value.imgs = ''
      dataForm.value.video = ''
    })
  }
}
// 表单提交
const deliveryMode = ref({
  hasShopDelivery: true,
  hasUserPickUp: false,
  hasCityDelivery: false
})
let partyCode = ''
let skuPartyCodes = false
const store = useCommonStore()
const onSubmit = () => {
  dataFormRef.value.validate(() => {
    if (!prodNameCn.value) {
      onErrorMsg($t('product.pleEnterProdName'))
      return
    }
    if (!dataForm.value.imgs) {
      onErrorMsg($t('product.plePictureToUpload'))
      return
    }
    // 校验sku列表
    onCheckSkuList()
    if (isCheck) {
      onErrorMsg(value)
      return
    }
    if ((dataForm.value.deliveryAmount === 0 || dataForm.value.deliveryAmount === '' || dataForm.value.deliveryAmount === null) && dataForm.value.tableRate === -1) {
      // 请选择运费模板
      onErrorMsg($t('menuList.pleaseEnterTheAmount'))
      return
    }
    if (dataForm.value.deliveryMode.hasShopDelivery && dataForm.value.tableRate > 0 && !dataForm.value.deliveryTemplateId) {
      // 请选择运费模板
      onErrorMsg($t('product.pleShgTlate'))
      return
    }

    dataForm.value.contentCn = contentCn.value
    dataForm.value.contentEn = contentEn.value
    if (validHtmlLength(dataForm.value.contentCn) || validHtmlLength(dataForm.value.contentEn)) {
      return
    }
    if ((dataForm.value.contentCn && dataForm.value.contentCn.length > 20000) || (dataForm.value.contentEn && dataForm.value.contentEn.length > 20000)) {
      return ElMessage({
        message: $t('product.tinyMceTip'),
        type: 'error',
        duration: 1500
      })
    }
    if (dataForm.value.tableRate === -1) {
      dataForm.value.deliveryTemplateId = -1
    } else if (dataForm.value.tableRate === 0) {
      dataForm.value.deliveryTemplateId = 0
    }

    dataForm.value.prodNameCn = prodNameCn.value
    dataForm.value.briefCn = briefCn.value
    dataForm.value.prodNameEn = prodNameEn.value || prodNameCn.value
    dataForm.value.briefEn = briefEn.value

    dataForm.value.prodName = dataForm.value.prodNameCn
    // sku名称为空时给空字符串
    dataForm.value.skuList.forEach((item) => {
      if (!item.skuName) {
        item.skuName = ''
        item.skuNameEn = ''
      }
    })
    const param = Object.assign({}, dataForm.value)
    // 设置价格和库存
    onSetPriceAndStocks(param)
    if (partyCode != null && partyCode !== '' && skuPartyCodes) {
      onErrorMsg('商品编码 ' + partyCode + ' 已存在，请输入新的编码')
      return
    }

    param.deliveryMode = undefined
    param.deliveryModeVo = deliveryMode.value
    dataForm.value.skuList.forEach(sku => {
      sku.changeStock = sku.stocks - sku.oriStock
    })
    // 商品主图
    param.pic = dataForm.value.imgs.split(',')[0]
    if (isSubmit) {
      return false
    }
    isSubmit = true
    http({
      url: http.adornUrl('/admin/scoreProduct'),
      method: param.prodId ? 'put' : 'post',
      data: http.adornData(param)
    }).then(() => {
      ElMessage({
        message: $t('remindPop.succeeded'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          store.removeMainActiveTab()
          router.push({ name: 'user/integrals-manage/score-prod-list/index' })
          emit('refreshDataList')
        }
      })
    }).catch(() => {
      isSubmit = false
    })
  })
}
let isCheck = false
const onCheckSkuList = () => {
  dataForm.value.skuList.forEach(item => {
    isCheck = false
    if (!item.price && item.price !== 0) {
      isCheck = true
      isValue = $t('product.emptyPrice')
      return false
    }
    if (!item.oriPrice && item.oriPrice !== 0) {
      isCheck = true
      isValue = $t('product.emptyMarketValue')
      return false
    }
    if (!item.skuScore) {
      isCheck = true
      isValue = $t('product.emptyScorePrice')
      return false
    }
    if (item.stocks == null) {
      isCheck = true
      isValue = $t('product.emptyStocks')
      return false
    }
  })
}
const onSetPriceAndStocks = (param) => {
  // 商品库存
  param.totalStocks = 0
  // 商品价格
  param.price = 0
  // 商品原价
  param.oriPrice = 0
  // 商品积分价格
  param.scorePrice = param.skuList[0].skuScore
  // 商品实际库存
  const partyCodes = []
  skuPartyCodes = false
  for (let i = 0; i < param.skuList.length; i++) {
    const element = param.skuList[i]
    if (element.partyCode != null && element.partyCode !== '' && partyCodes.indexOf(element.partyCode) !== -1) {
      partyCode = element.partyCode
      skuPartyCodes = true
      return false
    }
    partyCodes.push(element.partyCode)
    if (element.status !== 1) {
      continue
    }
    if (param.price === 0) {
      param.price = element.price ? Number.parseFloat(element.price) : 0
    }
    if (param.scorePrice === 0) {
      param.scorePrice = element.skuScore ? Number.parseFloat(element.skuScore) : 0
    }
    // 商品价格为最低价的那件商品的价格
    param.price = Math.min(param.price, element.price)
    if (param.price === parseFloat(element.price)) {
      param.scorePrice = element.skuScore
      param.oriPrice = element.oriPrice ? Number.parseFloat(element.oriPrice) : 0
    }
    param.totalStocks += element.stocks ? Number.parseInt(element.stocks) : 0
  }
  // 如果sku没有商品名称，则使用商品的商品名称
  if (param.skuList.length === 1) {
    param.skuList[0].prodNameCn = dataForm.value.prodNameCn
    param.skuList[0].prodNameEn = dataForm.value.prodNameEn
  }
}
const onChangeSkuTagSkuHandler = (skuList) => {
  const isProdNameCn = prodNameCn.value
  const isProdNameEn = prodNameEn.value
  skuList.forEach(sku => {
    if (sku.properties) {
      sku.skuName = ''
      const properties = sku.properties.split(';')
      for (const propertiesKey in properties) {
        sku.skuName += properties[propertiesKey].substring(properties[propertiesKey].indexOf(':') + 1) + ' '
      }
      sku.prodNameCn = isProdNameCn + ' ' + sku.skuName
      sku.prodNameEn = isProdNameEn + ' ' + sku.skuName
    }
  })
  dataForm.value.skuList = skuList
}
const onErrorMsg = (message) => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}
const onChangeInfo = (info) => {
  dataForm.value.deliveryTemplateId = info.transportId
  dataForm.value.tableRate = info.tableRate
  dataForm.value.deliveryAmount = info.deliveryAmount
}
/**
 * 删除视频
 */
const onDeleteVideo = () => {
  dataForm.value.video = ''
}

</script>

<style lang="scss" scoped>
.page-score-prod-info{
  .tiny-mce-width {
  width: 1000px !important;
}
@media (max-width:1660px) {
  .tiny-mce-width {
    width: 700px !important;
  }
}
  :deep(.el-form-item__content){
    display: block;
  }
  padding-bottom: 50px;
  // 步骤
  .post-step {
    margin-bottom: 30px;
    display: flex;
    align-content: center;
    justify-content: space-between;
    .step-item {
      position: relative;
      flex: 1;
      .step-txt {
        display: block;
        font-size: 14px;
        text-align: center;
        box-sizing: border-box;
        background: #f9f9f9;
        padding: 12px 0;
      }
    }
    .step-item.active {
      .step-txt {
        color: #fff;
        background: #155bd4;
      }
    }
    // 右箭头
    .step-item:not(:last-child) {
      .step-txt {
        margin-right: 10px;
      }
      &::after {
        position: absolute;
        top: 0;
        right: 0;
        content: '';
        width: 0;
        height: 0;
        border-top: 20px solid transparent;
        border-left: 10px solid #f9f9f9;
        border-bottom: 20px solid transparent;
      }
    }
    .step-item.active:not(:last-child) {
      &::after {
        border-left: 10px solid #155bd4;
      }
    }
    // 左箭头
    .step-item:not(:first-child) {
      &::before {
        position: absolute;
        top: 0;
        left: 0;
        content: '';
        width: 0;
        height: 0;
        border-top: 20px solid transparent;
        border-left: 10px solid #fff;
        border-bottom: 20px solid transparent;
      }
    }
  }
  /* 每项内容的标题 */
  .tittle {
    margin: 5px 0 28px 0;
    padding-left: 15px;
    background-color: #f6f6f6;
    line-height: 40px;
    font-weight: 800;
  }
  /* 每项内容盒子的设置 */
  .basic-info {
    margin-left: 35px;
  }
  & ::v-deep(.el-input__inner) {
    color: #303133;
  }
  // 底部固定操作栏
  .prod-footer {
    left: 250px;
    position: fixed;
    bottom: 0;
    width: 93%;
    box-shadow: 0 -3px 5px #eee;
    z-index: 3;
    margin-top: 20px;
    margin-right: 20px;
    .foot {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10px 0;
      background: #fff;
      box-sizing: border-box;
      .inner {
        .default-btn.save-btn {
          border-color: #155bd4;
          color: #155bd4;
        }
      }
    }
  }
  // 选择语言
  .select-lang {
    display: block;
    width: 400px;
  }

  // 商品名称
  .prod-name-box {
    & :deep(.el-input__inner) {
      width: 400px;
      padding: 0 8px!important;
    }
    .prod-name-con {
      // display: inline-block;
      margin-right: 15px;
    }
    .prod-name-input{
      display: block;
      width: 400px;
    }
  }

  .prod-det-box {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .prod-content {
      width: 60%;
      margin-right: 30px;

      // 富文本编辑框样式修改
      & :deep(.tinymce-container) {

        .mce-panel,
        .mce-container-body.mce-flow-layout {
          border-color: #DCDCDC !important;
        }

        .mce-edit-area {
          border-top: 0;
        }
      }
    }

    // 详情预览
    .details-preview {
      width: 40%;
      border: 1px solid #DCDCDC;
      box-sizing: border-box;

      .preview-box-title {
        height: 45px;
        line-height: 45px;
        background: #f9f9f9;
        text-align: center;
        border-bottom: 1px solid #DCDCDC;
      }

      .preview-con {
        height: 540px;
        overflow-y: auto;
        padding: 0 10px;
        word-wrap: break-word;
        box-sizing: border-box;
      }
    }

  }
}

</style>
